## Some commands and insigts of the book

> shell script profissional - Aurelio Marinho Jargas

> *escreva codigos legiveis, Cada minudo adicional investido em limpeza de codigo e documentacao compensa. Nao basta saber fazer bons algoritimos, eh preciso torna-los acessiveis!!* - Aurelio

```sh
$ history           # show the history of commands
$ man PROGRAM       # show the manual of the program that u've passed
$ PROGRAM --help    # help(?)
```

### clean code and documentation

#### **Header's**
* it's important to have a good documentation, a header, of the program that u're coding
* follow the writing recommendations for the language

*exemple of HEADER for a shell program:*
* *path* do interpretador
* program name
* rapid description
* program site/repo
* author's name
* author's email
* description of how it works
    * how it work
    * examples
    * tests
* data of the creation
* history of changing
* lisense

**EXAMPLE:**
```sh
#!/bin/bash
#
# complete_name.sh - search for the name of the linux user
#
# Site  : https://program-site.com/repositorio
# Athor : Someone <someone@email.com.br>
#
# -------------------------------------------------------
#   This program make this... Lorem ipsum dolor sit amet,
#   consectetur adipiscing elit. Suspendisse elementum arcu
#   eu ligula mollis ornare. 
#   Integer felis risus, pellentesque ac turpis eget, pretium
#   finibus leo. Duis sed tortor egestas sem ornare faucibus
#   vitae a leo. Praesent id maximus arcu. Nunc sit amet enim sollicitudin
#
#   Examples:
#     $ ./inputs
#     outputs
#
#   Other informations...:
#     1. something
#     2. anotherthing
#
#   And then some other things(?)
# -------------------------------------------------------
#
# History:
#
# v1.0 2000-01-12, Someone:
#   - Alteration made
#
# v1.1 2000-02-01, Someone:
#   - Alteration made
#   - other alteration
#
#
# Lisence: GPL.

# then the code
```

#### **Using block comments**

its so cute <3

```sh
#####################################################
#                                                   #
#   this is a block comment                         #
#                                                   #
#   why a so long comment(?)                        #
#   i don't know why, but it's sounds               #
#   very useful and beatiful too                    #
#                                                   #
#####################################################
```

---
### using flags

like a key, a flags :P switch, on and of something

> u can use keys to change whole aspects of the program, just the initial state will be considered, and then, update the whole code

**obs:** use 0 or 1 as values for flags
```sh
$ test "$flag" = 1 && echo ON   # this will apply the comparation to a STRING to a NUMBER or a STRING :P better <3
```

---
### line commands options

don't have a default at all, but have a template:

```sh
-<word>     = -name, -type
letter      = a u w x
<word>=     = if=, of=, count=
```

**some of the classics...**
```sh
-h, --help      : show a short information about the program
-V, --version   : show the version of the program (V uppercase)
-v, --verbose   : show extra info on the output
-q, --quiet     : don't show a exit, a quiet exuction
```

The order of the parameters are:
```sh
    cut -d  :   -f  2   /etc/passwd
    $0  $1  $2  $3  $4  $5
```

---
### multiple string lines (messages like """---""" on python...)

just a string with the format passed on the string

```sh
MESSAGE = "
    every tab
every line
            everything will be printed
"
```

---
### operations

The test command in Linux evaluates conditional expressions and often pairs with the Bash if statement. There are two variations for the test syntax:

```sh
test 2 -gt 3; # something
```

**arithmetic expressions:**
```sh
if (("$age" < 7 || "$age" > 65)) ; then
    echo " You can walk in for free "
elif (( "$age" > 7 && "$age" < 65 )) ; then
    echo " You have to pay for ticket "
fi
```

****
---
### if, else, elif states
```sh
if test "SOMETHING" OPERATION "OTHER VAR"
then
    # code
elif test "SOMETHING" OPERATION "OTHER VAR"
then
    # code
fi
```

---
### shift state

when u' are working with parameters, u' can pass them like to a queue, u pass the $2, to the $1 position....

```sh
while test -n "$1"
do
  ### do what it have to do...
  shift
done
```
---
### case state
```sh
case "SOMETHING" in
  SOMETHING)
    # code
  ;;

  SOMETHING)
    # code
  ;;

  *)
    # default
  ;;
esac
```

### Debug

for the context, debug is fixing bugs, clean, and make it simple.

* some of the techniques, and what to search for:
  * verify the sintax
    * -n
  * execute the step by step
  * simple debug
    * using echo (or outputs)
  * sectorized debug
    * using *set*
  * custom debug
  * categorized debug

**verify the sintaxe erros:**
* if it return a erro will show the line and the code, if not will not output nothing
```sh
bash  -n PROGRAM-NAME
```

**global debug**
* it'll execute the code step by step
```sh
bash -x PROGRAM-NAME
# + TXT=scream
# + TXT='   scream    '
# + echo '   scream    '
#    scream    
# ++ echo '   scream    '
# ++ tr ' ' '!'
# + TXT='!!!scream!!!!'
# + echo '!!!scream!!!!'
# !!!scream!!!!
# ++ echo '!!!scream!!!!'
# ++ tr a-z A-Z
# + TXT='!!!SCREAM!!!!'
# + echo '!!!SCREAM!!!!'
# !!!SCREAM!!!!

bash -v PROGRAM-NAME
# #!/bin/bash
# # scream.sh
# #
# # showt the word ($TXT) in CAPS
# # and with !!!
# #
# # example
# #     foo -> !!!!FOO!!!!
# #

# TXT="scream"

# TXT="   $TXT    "                   # add 5 spaces
# echo "$TXT"
#    scream    
# TXT=$(echo "$TXT" | tr " " "!")     # change the spaces to !
# echo "$TXT"
# !!!scream!!!!
# TXT=$(echo "$TXT" | tr a-z A-Z)     # turn to Upper case

# echo "$TXT"                         # show the message
# !!!SCREAM!!!!

bash -xv PROGRAM-NAME
# #!/bin/bash
# # scream.sh
# #
# # showt the word ($TXT) in CAPS
# # and with !!!
# #
# # example
# #     foo -> !!!!FOO!!!!
# #

# TXT="scream"
# + TXT=scream

# TXT="   $TXT    "                   # add 5 spaces
# + TXT='   scream    '
# echo "$TXT"
# + echo '   scream    '
#    scream    
# TXT=$(echo "$TXT" | tr " " "!")     # change the spaces to !
# ++ echo '   scream    '
# ++ tr ' ' '!'
# + TXT='!!!scream!!!!'
# echo "$TXT"
# + echo '!!!scream!!!!'
# !!!scream!!!!
# TXT=$(echo "$TXT" | tr a-z A-Z)     # turn to Upper case
# ++ echo '!!!scream!!!!'
# ++ tr a-z A-Z
# + TXT='!!!SCREAM!!!!'

# echo "$TXT"                         # show the message
# + echo '!!!SCREAM!!!!'
# !!!SCREAM!!!!
```

### Quotation
* if u use "$variable" it'll return the full varible value
* if u use $varible, it'll clean the output (remove the spaces) like:
```sh
test="09283   lsadj f a     aldsf      fal;jks    "
echo $test    # 09283 lsadj f a aldsf fal;jks
echo "$test"  # 09283   lsadj f a     aldsf      fal;jks    
```
### sectorized debug
* using set like:
```sh
set -x # turn on
set +x # turn off
set -v # turn on
set +v # turn off
```
---

### Cursor positions

> the base is: `ESC[<quantity><command>`

some of them:
* `ESC[nA` => cursor up *n* lines in the current column
* `ESC[nB` => cursor down *n* lines in the current column
* `ESC[nC` => cursor right *n* lines in the current column
* `ESC[nD` => cursor left *n* lines in the current column
* `ESC[nE` => cursor down *n* lines in the 1 column
* `ESC[nF` => cursor up in the 1 column
* `ESC[nA` => cursor to the *n* column in the current line
* `ESC[n;mH` => move to the column *m* on the *n* line

---

### regex

> regular expressions

```txt
^ => representa o comeco da linha
$ => representa o final da linha
---
[abc] => casa as letras "a" ou "b" ou "c"
[a-d] => casa as letras "a" ou "b" ou "c" ou "d"
[^abc] => casa qualquer char exeto "a", "b" e "c"
(esse|aquele) => casa as strings "esse" ou "aquele"
---
a{2} => casa a letra "a" duas vezes
a{2,4} => casa a letra "a" duas a 4 vezes
a{2,} => casa a letra "a" no minimo 2 vezes
a? => casa a letra "a" zero ou mais vezes
a* => casa a letra "a" zero ou mais vezes
a+ => casa a letra "a" uma ou mais vezes
---
. => casa um char qualquer
.* => casa qualquer coisa, eh o tudo e o nada
```

### commands

---
**test**

```sh
$ test      # test will compare two NUMBERS (will output a error if have a value diferent of a NUMBER)

$ test "$flag" = 1 && echo ON   # this will apply the comparation to a STRING to a NUMBER or a STRING :P better <3
```
---
**grep**

---
**sort**

---
**cut**

> Its purpose in life is to snip out sections of text from files or streams, according to the criteria that you set. Its syntax is as simple as its purpose, but it is this joint simplicity that makes it so useful.

```sh
$ cut -d "FILTER" -f NUMBER_OF_FIELDS       # take the filter with the F fields
```

--- 
**tr**
> tr is a command-line utility in Linux and Unix systems that translates, deletes, and squeezes characters from the standard input and writes the result to the standard output.

```sh
# tr OPTION... SET1 [SET2]
echo 'linuxize' | tr 'lin' 'red' # reduxeze
echo 'Linuxize' | tr -d 'liz' # remove the liz chars: Lnuxe
echo "GNU     \    Linux" | tr -s ' ' # remove the spaces
```

---
**dd**

> dd command in Linux can be very handy in many situations, as it can be used to convert and copy files in the terminal, backup disks, or wipe data. 

* if (input!!)
* of (output!!)

```sh
# backup
dd if=/dev/sdX of=/dev/sdY

# all the file to upper or to lower
dd if=commands.txt of=commands.caps conv=ucase # or lcase

# clean the disk
dd if=/dev/zero of=/dev/sdX

# create a bootable mem stick
dd if=/img.iso of=/dev/sdX -v

```